package com.huawei.esdk.tp.business.common.confmgr;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.huawei.esdk.platform.common.SDKErrorCode;
import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.config.ConfigManager;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.common.utils.StringUtils;
import com.huawei.esdk.tp.base.BaseService;
import com.huawei.esdk.tp.common.ErrInfo;
import com.huawei.esdk.tp.domain.model.Conference;
import com.huawei.esdk.tp.domain.model.ScheduleConference;
import com.huawei.esdk.tp.domain.model.Site;
import com.huawei.esdk.tp.domain.model.SiteInConference;
import com.huawei.esdk.tp.domain.model.SiteInfoCommService;

public class ConfMgrService extends BaseService
{
    private static final Logger LOGGER = Logger.getLogger(ConfMgrService.class);

    private SiteInfoCommService siteInfoCommService;

    public SiteInfoCommService getSiteInfoCommService()
    {
        return siteInfoCommService;
    }

    public void setSiteInfoCommService(SiteInfoCommService siteInfoCommService)
    {
        this.siteInfoCommService = siteInfoCommService;
    }

    public SDKResult<String> addSiteToScheduledConf(String confId,
            String siteUri) throws SDKException
    {
        SDKResult<String> result = new SDKResult<String>();
        if (StringUtils.isEmpty(confId))
        {
            LOGGER.debug("confId is null");
            result.setErrCode(ErrInfo.CONF_ID_ISNULL_ERRORCODE);
            return result;
        }
        if (!StringUtils.isUintNumber(confId))
        {
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }

        // 准备Model Bean：本接口涉及ScheduleConference和Site两个领域模型
        ScheduleConference scheduleConference = new ScheduleConference(confId);
        Site site = new Site(siteUri);

        Site siteInfo = null;

        if ("".equals(siteUri))
        {
            // 1.会场uri为空字符串("")，允许添加，当做匿名会场来处理，会场需要的默认值由SDK来指定，可通过配置文件配置
            site.setName(ConfigManager.getInstance()
                    .getValue("common.addSiteToScheduledConf.anonymousSiteName"));
            site.setSiteType(ConfigManager.getInstance()
                    .getValue("common.addSiteToScheduledConf.SiteType"));
            site.setDialingMode(ConfigManager.getInstance()
                    .getValue("common.scheduleConf.dialingMode"));
        }
        else
        {
            // 通过SiteUri查询会场详细信息
            siteInfo = siteInfoCommService.getSite(siteUri);
            if (null == siteInfo)
            {
                // 2.会场uri未在SMC中注册，允许添加，会场需要的默认值由SDK来指定，可通过配置文件配置
                site.setName(ConfigManager.getInstance()
                        .getValue("common.addSiteToScheduledConf.unregisteredSiteName"));
                site.setSiteType(ConfigManager.getInstance()
                        .getValue("common.addSiteToScheduledConf.SiteType"));
                site.setDialingMode(ConfigManager.getInstance()
                        .getValue("common.scheduleConf.dialingMode"));
            }
            else
            {
                // 3.会场uri已在SMC中注册，允许添加，会场需要的默认值需要根据SMC中会场信息来给定，如Name和SiteType
                site.setName(siteInfo.getName());
                site.setSiteType(siteInfo.getSiteType());
                site.setDialingMode(ConfigManager.getInstance()
                        .getValue("common.scheduleConf.dialingMode"));
            }
        }

        // 调用Model
        SDKResult<ScheduleConference> scheduleConferenceResponse = null;
        scheduleConferenceResponse = scheduleConference
                .addSite(
                        site,
                        Boolean.parseBoolean(ConfigManager.getInstance()
                                .getValue("common.addSiteToScheduledConfImpl.IsUseAnonymousSite")));

        result = new SDKResult<String>();
        result.setErrCode(scheduleConferenceResponse.getErrCode());
        if (0 == result.getErrCode())
        {
            // 找出新增会场对应的confAccessCode，并在SDKResult中返回
            for (SiteInConference siteInConference : scheduleConferenceResponse
                    .getResult().getSites())
            {
                if (siteInConference.getUri().equals(siteUri))
                {
                    result.setResult(siteInConference.getConfAccessCode());
                    break;
                }
            }
        }

        return result;
    }

    public SDKErrorCode delSiteFromScheduledConf(String confId, String siteUri) throws SDKException
    {
        SDKErrorCode errorCode = new SDKErrorCode();

        if (StringUtils.isEmpty(confId))
        {
            errorCode.setErrCode(ErrInfo.CONF_ID_ISNULL_ERRORCODE);
            return errorCode;
        }
        if (StringUtils.isEmpty(siteUri))
        {
            errorCode.setErrCode(ErrInfo.SITE_URI_ISNULL_ERRORCODE);
            return errorCode;
        }
        if (!StringUtils.isUintNumber(confId))
        {
            errorCode.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return errorCode;
        }

        // 准备Model Bean
        ScheduleConference scheduleConference = new ScheduleConference(confId);

        SiteInConference site = new SiteInConference(siteUri);
        
        // 调用Model
        SDKErrorCode result = scheduleConference.removeSite(site);

        return result;
    }

    public SDKErrorCode cancelScheduledConf(String confId) throws SDKException
    {
        SDKErrorCode errorCode = new SDKErrorCode();

        if (StringUtils.isEmpty(confId))
        {
            errorCode.setErrCode(ErrInfo.CONF_ID_ISNULL_ERRORCODE);
            return errorCode;
        }
        if (!StringUtils.isUintNumber(confId))
        {
            errorCode.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return errorCode;
        }
        Conference conf = new Conference(confId);
        errorCode = conf.deleteConference();

        return errorCode;
    }

    public SDKResult<List<SiteInConference>> queryConfSitesStatus(
            String confId, List<String> siteUris) throws SDKException
    {
        SDKResult<List<SiteInConference>> result = new SDKResult<List<SiteInConference>>();
        // 进行参数判断
        if (StringUtils.isEmpty(confId))
        {
            result.setErrCode(ErrInfo.CONF_ID_ISNULL_ERRORCODE);
            return result;
        }

        if (!StringUtils.isUintNumber(confId))
        {
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }
        // 准备Model
        SiteInConference siteInConference = new SiteInConference();
        // 将request的值赋给Model
        siteInConference.setConfId(confId);
        siteInConference.setSiteUris(siteUris);
        // 调用领域bean方法
        result = siteInConference.querySitesStatusInConference(siteUris);

        return result;
    }

    // /////////////////////////////////////

    /**
     * 修改会议 解耦service，默认值，组合接口，消息校验都在这里处理
     * @throws SDKException 
     */
    public SDKResult<ScheduleConference> editScheduleConfResponseService(
            ScheduleConference conference) throws SDKException
    {
        // 校验必填参数
        SDKResult<ScheduleConference> result = new SDKResult<ScheduleConference>();
        if (StringUtils.isEmpty(conference.getId())
                || StringUtils.isEmpty(conference.getName())
                || null == conference.getBeginTime()
                || null == conference.getLength())
        {
            // 必填参数不全
            result.setErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
            return result;
        }
        // 校验参数类型
        if (!StringUtils.isUintNumber(conference.getId()))
        {
            // 参数类型错误
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }

        List<SiteInConference> sites = conference.getSites();
            // 修改会议，如果有一个会场uri为空，视为必填参数不全;通过会场uri查询会场的名称，type
            for (int k = 0; k < sites.size(); k++)
            {
                SiteInConference siteInConference = sites.get(k);
                String siteUri = siteInConference.getUri();
                String siteTypeDefault = ConfigManager.getInstance()
                        .getValue("common.scheduleDynamicSiteConfImpl.siteType");
                if (StringUtils.isEmpty(siteUri))
                {
                    // 视为匿名会场，修改会议的时候可以添加匿名会场
                    siteInConference.setSiteType(siteTypeDefault);
                    sites.set(k, siteInConference);
                    continue;
                }

                Site siteInfo = siteInfoCommService.getSite(siteUri);
                if (null == siteInfo)
                {
                    // 会场uri没有在SMC中记录，会场不存在
                    result.setErrCode(ErrInfo.SITE_NOT_EXIST_ERRORCODE);
                    return result;
                }
                siteInConference.setName(siteInfo.getName());
                siteInConference.setSiteType(siteInfo.getSiteType());

                // 给会场中的from,dialMode赋值，如果用户填写了值，按照用户填写的取值，如果是空，写入默认值
                String fromDefault = ConfigManager.getInstance()
                        .getValue("common.scheduleConf.from");
                siteInConference
                        .setFrom(null == siteInConference.getFrom() ? fromDefault
                                : siteInConference.getFrom());
                String dialingModeDefault = ConfigManager.getInstance()
                        .getValue("common.scheduleConf.dialingMode");
                siteInConference.setDialingMode(null == siteInConference
                        .getDialingMode() ? dialingModeDefault
                        : siteInConference.getDialingMode());

                sites.set(k, siteInConference);
            }

            // 准备Model
            ScheduleConference scheduleConference = new ScheduleConference();
            // 设置默认值
            if (StringUtils.isEmpty(conference.getRate()))
            {
                conference.setRate("1920K");
            }
            // 调用model
            result = scheduleConference.reschedule(conference);

        return result;
    }
    /**
     * 解耦service，默认值，组合接口，消息校验都在这里处理
     * @throws SDKException 
     */
    public SDKResult<ScheduleConference> scheduleImmediateConfResponseService(
            ScheduleConference conference) throws SDKException
    {
        // 校验必填参数
        boolean isEmpty = false;
        if (StringUtils.isEmpty(conference.getName())
                || null == conference.getLength())
        {
            isEmpty = true;
        }

        List<SiteInConference> sites = conference.getSites();
        SDKResult<ScheduleConference> result = new SDKResult<ScheduleConference>();
        // 校验参数类型
        if (!StringUtils.isEmpty(conference.getId())&&!StringUtils.isUintNumber(conference.getId()))
        {
            // 参数类型错误
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }
        //即时会议，设置时间为系统当前时间
        conference.setBeginTime(new Date());
            // 预约会议，如果有一个会场uri为空，视为必填参数不全;通过会场uri查询会场的名称，type
            for (int k = 0; k < sites.size(); k++)
            {
                SiteInConference siteInConference = sites.get(k);
                String siteUri = siteInConference.getUri();
                if (StringUtils.isEmpty(siteUri))
                {
                    isEmpty = true;
                    break;
                }
                else
                {
                    Site siteInfo = siteInfoCommService.getSite(siteUri);
                    if (null == siteInfo)
                    {
                        // 会场uri没有在SMC中记录，会场不存在
                        result.setErrCode(ErrInfo.SITE_NOT_EXIST_ERRORCODE);
                        return result;
                    }
                    siteInConference.setName(siteInfo.getName());
                    siteInConference.setSiteType(siteInfo.getSiteType());

                    // 给会场中的from,dialMode赋值，如果用户填写了值，按照用户填写的取值，如果是空，写入默认值
                    String fromDefault = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.from");
                    siteInConference
                            .setFrom(null == siteInConference.getFrom() ? fromDefault
                                    : siteInConference.getFrom());
                    String dialingModeDefault = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.dialingMode");
                    siteInConference.setDialingMode(null == siteInConference
                            .getDialingMode() ? dialingModeDefault
                            : siteInConference.getDialingMode());

                    sites.set(k, siteInConference);
                }
            }
            // 必填参数不全
            if (isEmpty)
            {
                result.setErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
                return result;
            }

            // 准备Model
            ScheduleConference scheduleConference = new ScheduleConference();
            // 设置默认值
            if (StringUtils.isEmpty(conference.getRate()))
            {
                conference.setRate("1920K");
            }
            conference.setSites(sites);
            // 调用model
            result = scheduleConference.schedule(conference);

        return result;
    }
    /**
     * 延长会议
     * @param confId
     * @param prolongTime
     * @return
     * @throws SDKException 
     */
    public SDKErrorCode prolongScheduleConf(String confId, Integer prolongTime) throws SDKException
    {
        SDKErrorCode result = new SDKErrorCode();

        if (StringUtils.isEmpty(confId))
        {
            // 必填参数不全
            result.setErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
            return result;
        }
        // 校验参数类型
        if (!StringUtils.isUintNumber(confId))
        {
            // 参数类型错误
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }
            // 准备Model
            ScheduleConference scheduleConference = new ScheduleConference();
            scheduleConference.setId(confId);
            // 调用model
            result = scheduleConference.prolong(confId, null, prolongTime);

        return result;
    }

    /**
     * 解耦service，默认值，组合接口，消息校验都在这里处理
     * @throws SDKException 
     */
    public SDKResult<ScheduleConference> scheduleConfResponseService(
            ScheduleConference conference) throws SDKException
    {
        // 校验必填参数
        boolean isEmpty = false;
        if (StringUtils.isEmpty(conference.getName())
                || null == conference.getBeginTime()
                || null == conference.getLength())
        {
            isEmpty = true;
        }

        List<SiteInConference> sites = conference.getSites();
        SDKResult<ScheduleConference> result = new SDKResult<ScheduleConference>();
            // 预约会议，如果有一个会场uri为空，视为必填参数不全;通过会场uri查询会场的名称，type
        // 校验参数类型
        if (!StringUtils.isEmpty(conference.getId())&&!StringUtils.isUintNumber(conference.getId()))
        {
            // 参数类型错误
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }
            for (int k = 0; k < sites.size(); k++)
            {
                SiteInConference siteInConference = sites.get(k);
                String siteUri = siteInConference.getUri();
                if (StringUtils.isEmpty(siteUri))
                {
                    isEmpty = true;
                    break;
                }
                else
                {
                    Site siteInfo = siteInfoCommService.getSite(siteUri);
                    if (null == siteInfo)
                    {
                        // 会场uri没有在SMC中记录，会场不存在
                        result.setErrCode(ErrInfo.SITE_NOT_EXIST_ERRORCODE);
                        return result;
                    }
                    siteInConference.setName(siteInfo.getName());
                    siteInConference.setSiteType(siteInfo.getSiteType());

                    // 给会场中的from,dialMode赋值，如果用户填写了值，按照用户填写的取值，如果是空，写入默认值
                    String fromDefault = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.from");
                    siteInConference
                            .setFrom(null == siteInConference.getFrom() ? fromDefault
                                    : siteInConference.getFrom());
                    String dialingModeDefault = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.dialingMode");
                    siteInConference.setDialingMode(null == siteInConference
                            .getDialingMode() ? dialingModeDefault
                            : siteInConference.getDialingMode());

                    sites.set(k, siteInConference);
                }
            }
            // 必填参数不全
            if (isEmpty)
            {
                result.setErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
                return result;
            }

            // 准备Model
            ScheduleConference scheduleConference = new ScheduleConference();
            // 设置默认值
            if (StringUtils.isEmpty(conference.getRate()))
            {
                conference.setRate("1920K");
            }
            conference.setSites(sites);
            // 调用model
            result = scheduleConference.schedule(conference);

        return result;
    }

    /**
     * 解耦service，默认值，组合接口，消息校验都在这里处理
     * @throws SDKException 
     */
    public SDKResult<ScheduleConference> scheduleDynamicSiteConfService(
            ScheduleConference conference) throws SDKException
    {
        // 校验必填参数
        // 预约带匿名会场的会议，如果不存在一个会场uri为空，视为必填参数不全
        SDKResult<ScheduleConference> result = new SDKResult<ScheduleConference>();
        // 校验参数类型
        if (!StringUtils.isEmpty(conference.getId())&&!StringUtils.isUintNumber(conference.getId()))
        {
            // 参数类型错误
            result.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return result;
        }
        if (StringUtils.isEmpty(conference.getName())
                || null == conference.getBeginTime()
                || null == conference.getLength())
        {
            result.setErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
            return result;
        }
        List<SiteInConference> sites = conference.getSites();

            boolean containDynamic = false;
            Site siteInfo = null;
            String siteType = null;
            String dialMode = null;
            String from = null;
            for (int k = 0; k < sites.size(); k++)
            {
                SiteInConference siteInConference = sites.get(k);
                String siteUri = siteInConference.getUri();
                if (StringUtils.isEmpty(siteUri))
                {
                    containDynamic = true;
                    // 如果用户填写了siteType类型，按照用户填写的处理，否则写默认值
                    siteType = ConfigManager.getInstance()
                            .getValue("common.scheduleDynamicSiteConfImpl.siteType");
                    from = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.from");
                    dialMode = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.dialingMode");

                    if (StringUtils.isEmpty(siteInConference.getSiteType()))
                    {
                        siteInConference.setSiteType(siteType);
                    }
                    if (StringUtils.isEmpty(siteInConference.getDialingMode()))
                    {
                        siteInConference.setDialingMode(dialMode);
                    }
                    if (StringUtils.isEmpty(siteInConference.getFrom()))
                    {
                        siteInConference.setFrom(from);
                    }
                    sites.set(k, siteInConference);
                }
                else
                {
                    siteInfo = siteInfoCommService.getSite(siteUri);
                    if (null == siteInfo)
                    {
                        // 会场uri没有在SMC中记录，会场不存在
                        result.setErrCode(ErrInfo.SITE_NOT_EXIST_ERRORCODE);
                        return result;
                    }
                    siteInConference.setName(siteInfo.getName());
                    siteInConference.setSiteType(siteInfo.getSiteType());

                    // 给会场中的from,dialMode赋值，如果用户填写了值，按照用户填写的取值，如果是空，写入默认值
                    String fromDefault = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.from");
                    siteInConference
                            .setFrom(null == siteInConference.getFrom() ? fromDefault
                                    : siteInConference.getFrom());
                    String dialingModeDefault = ConfigManager.getInstance()
                            .getValue("common.scheduleConf.dialingMode");
                    siteInConference.setDialingMode(null == siteInConference
                            .getDialingMode() ? dialingModeDefault
                            : siteInConference.getDialingMode());

                    sites.set(k, siteInConference);
                }
            }
            // 不包含匿名会场
            if (!containDynamic)
            {
                result.setErrCode(ErrInfo.CONF_ISDYNAMICSITE_ERRORCODE);
                return result;
            }

            // 准备Model
            ScheduleConference scheduleConference = new ScheduleConference();
            // 设置默认值
            if (StringUtils.isEmpty(conference.getRate()))
            {
                conference.setRate("1920K");
            }
            // 调用model
            result = scheduleConference.schedule(conference);

        return result;
    }

    public SDKResult<Conference> queryConferencesStatus(String confId) throws SDKException
    {
        SDKResult<Conference> sdkResult = new SDKResult<Conference>();
        if (StringUtils.isEmpty(confId))
        {
            sdkResult.setErrCode(ErrInfo.CONF_ID_ISNULL_ERRORCODE);
            return sdkResult;
        }
        if (!StringUtils.isUintNumber(confId))
        {
            sdkResult.setErrCode(ErrInfo.CONF_ID_IS_INVALID_ERRORCODE);
            return sdkResult;
        }
        List<String> confIds = new ArrayList<String>();
        confIds.add(confId);

        SDKResult<List<Conference>> result = Conference
                .queryConferencesStatus(confIds);
        sdkResult.setErrCode(result.getErrCode() == 1347420162 ? 0 : result
                .getErrCode());
        if (null != result.getResult() && result.getResult().size() > 0)
        {
            sdkResult.setResult(result.getResult().get(0));
        }
        return sdkResult;
    }
}
